package com.atguigu.srb.core.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.srb.core.hfb.RequestHelper;
import com.atguigu.srb.core.mapper.LendItemMapper;
import com.atguigu.srb.core.pojo.entity.LendItem;
import com.atguigu.srb.core.pojo.entity.TransFlow;
import com.atguigu.srb.core.service.LendItemService;
import com.atguigu.srb.core.service.LendService;
import com.atguigu.srb.core.service.TransFlowService;
import com.atguigu.srb.core.service.UserAccountService;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;

/**
 * <p>
 * 标的出借记录表 服务实现类
 * </p>
 *
 * @author Atguigu
 * @since 2024-04-15
 */
@Service
public class LendItemServiceImpl extends ServiceImpl<LendItemMapper, LendItem> implements LendItemService {
    @Resource
    private TransFlowService transFlowService;
    @Resource
    private LendService lendService;
    @Resource
    private UserAccountService userAccountService;
    @Override
    public String investNotify(Map<String, Object> map) {
        String resultCode = map.get("resultCode").toString();
        String lendItemNo = map.get("agentBillNo").toString(); // lendItemNo
        String lendId = map.get("agentProjectCode").toString();
        String voteBindCode = map.get("voteBindCode").toString();
        BigDecimal voteAmt = new BigDecimal(map.get("voteAmt").toString());
        String sign = map.get("sign").toString();
        // 1. 校验签名
        if(!RequestHelper.isSignEquals(map)){
            return "fail";
        }
        // 2. 处理投资结果
        if (!"0001".equals(resultCode)){
            return "fail";
        }
        // 3. 比对实际投资金额与提交的投资金额
        TransFlow transFlow = transFlowService.getOne(Wrappers.lambdaQuery(TransFlow.class)
                .eq(TransFlow::getTransNo, lendItemNo));
        if(voteAmt.compareTo(transFlow.getTransAmount())!=0){
            return "fail";
        }
        // 4. 回调接口可能会被多次调用，为了保证幂等性，修改交易日志的状态
        transFlow.setMemo(JSON.toJSONString(map));
        transFlow.setUpdateTime(null);
        transFlow.setIsUsed(1);
        transFlowService.updateById(transFlow);
        // 5. 更新投资记录
        this.update(Wrappers.lambdaUpdate(LendItem.class).set(LendItem::getStatus,1)
                .set(LendItem::getUpdateTime,new Date()).eq(LendItem::getLendItemNo,lendItemNo));
        // 6. 更新标的
        //  投资人数，已投金额
        lendService.updateLendInvestAmountAndNumber(lendId,voteAmt);
        // 7. 更新账户余额
        userAccountService.updateBalanceAndFreezeMoney(voteAmt,transFlow.getUserId());
        return "success";
    }
}
